import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import {
    Card,
    Button,
    Form,
    Input,
    InputNumber,
    Row,
    Col,
    Select,
    message,
    Spin,
    Typography,
    Divider,
    Space,
    Result,
    Statistic,
    Empty,
} from 'antd';
import { history, useSearchParams } from '@umijs/max';
import { ArrowLeftOutlined, ShoppingCartOutlined } from '@ant-design/icons';
import AddOrderProductCard from '@/components/AddOrderProductCard';
import { getProductList } from '@/services/ant-design-pro/product';
import { getRestaurantTables } from '@/services/ant-design-pro/desk';
import { createTrade, previewTradePrice, printTradeTicket } from '@/services/order';

const { Title, Text } = Typography;
const { Option } = Select;

const OrderFormPage: React.FC = () => {
    const [orderForm] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [submitting, setSubmitting] = useState(false);
    const [orderSuccess, setOrderSuccess] = useState(false);
    const [createdOrderId, setCreatedOrderId] = useState<number | null>(null);
    const [productList, setProductList] = useState<any[]>([]);
    const [tableList, setTableList] = useState<any[]>([]);
    const [orderPreview, setOrderPreview] = useState<any>(null);
    const searchParams = useSearchParams();
    const tableId = searchParams[0].get('tableId');
    console.log('[tableId]', tableId);

    const [orderParams, setOrderParams] = useState<Record<string, any>>({
        channel: 'minipro',
        restaurantId: window.MERCHANT_ID,
        tableId: Number(tableId),
    });

    console.log('orderParams', orderParams)


    // 加载商品列表
    const initProductList = async (params = {}) => {
        setLoading(true);
        try {
            const resp = await getProductList({ ...params, status: 1, page: 1, pageSize: 100 });
            const { list } = resp?.data;
            console.log('[list]', list);
            setProductList(list);
        } catch (error) {
            console.error('加载商品列表失败', error);
            message.error('加载商品列表失败');
        } finally {
            setLoading(false);
        }
    };

    // 加载餐桌列表
    const initTableList = async () => {
        try {
            const resp = await getRestaurantTables({});
            const { list } = resp?.data;
            setTableList(list);
        } catch (error) {
            console.error('加载餐桌列表失败', error);
            message.error('加载餐桌列表失败');
        }
    };

    // 预览订单价格
    const handlePreviewPrice = async (tradeOrderList: any[]) => {
        if (!tradeOrderList || tradeOrderList.length === 0) {
            setOrderPreview(null);
            return;
        }

        try {
            const resp = await previewTradePrice({ ...orderParams, tradeOrderList });
            if (resp?.code === 0) {
                setOrderPreview(resp?.data);
            }
        } catch (error) {
            console.error('预览订单价格失败', error);
        }
    };

    // 提交订单
    const handleSubmit = async () => {
        try {
            await orderForm.validateFields();

            if (!orderParams.tradeOrderList || orderParams.tradeOrderList?.length === 0) {
                message.warning('请先添加商品');
                return;
            }

            if (!orderParams.tableId) {
                message.warning('请选择餐桌');
                return;
            }

            setSubmitting(true);
            const resp = await createTrade(orderParams);

            if (resp?.code === 0) {
                setCreatedOrderId(resp?.data?.id);
                message.success('下单成功');
                setOrderSuccess(true);

                // 自动打印小票
                if (localStorage.getItem('disableOrderPrint') !== 'true') {
                    try {
                        const printResp = await printTradeTicket(resp?.data?.id);
                        if (printResp.code === 0) {
                            message.success('小票打印成功');
                        }
                    } catch (error) {
                        console.error('打印小票失败', error);
                        message.error('打印小票失败');
                    }
                }
            } else {
                message.error(resp?.message || '下单失败');
            }
        } catch (error) {
            console.error('提交订单失败', error);
            message.error('表单验证失败，请检查填写的信息');
        } finally {
            setSubmitting(false);
        }
    };

    // 返回列表页
    const handleBack = () => {
        history.back();
    };

    // 清空表单
    const handleReset = () => {
        orderForm.resetFields();
        setOrderParams({
            channel: 'minipro',
            restaurantId: window.MERCHANT_ID,
        });
        setOrderPreview(null);
    };

    // 查看已创建的订单
    const viewOrder = () => {
        if (createdOrderId) {
            history.push(`/order/detail/${createdOrderId}`);
        }
    };

    // 继续下单
    const continueOrder = () => {
        setOrderSuccess(false);
        handleReset();
        setCreatedOrderId(null);
    };

    useEffect(() => {
        initProductList();
        initTableList();
    }, []);

    // 渲染成功页面
    const renderSuccess = () => (
        <Result
            status="success"
            title="订单创建成功!"
            subTitle={`订单ID: ${createdOrderId}`}
            extra={[
                <Button type="primary" key="view" onClick={viewOrder}>
                    查看订单
                </Button>,
                // <Button key="continue" onClick={continueOrder}>
                //     继续下单
                // </Button>,
                <Button key="back" onClick={() => {
                    history.push(`/desk/order`);
                }}>
                    返回点餐台
                </Button>
            ]}
        />
    );

    // 渲染下单表单
    const renderOrderForm = () => (
        <Spin spinning={loading || submitting}>
            <Row gutter={[24, 24]}>
                <Col xs={24} lg={24}>
                    <AddOrderProductCard
                        defaultProductList={productList}
                        onChange={(tradeOrderList: any) => {
                            console.log('[tradeOrderList]', tradeOrderList);
                            setOrderParams({
                                ...orderParams,
                                tradeOrderList,
                            });
                            handlePreviewPrice(tradeOrderList);
                        }}
                    />

                    <Card title="基础信息" style={{ marginTop: 24 }} bordered={false}>
                        <Form
                            form={orderForm}
                            layout="vertical"
                            onValuesChange={(changedValues, allValues) => {
                                setOrderParams({ ...orderParams, ...allValues });
                            }}
                            initialValues={{ tableId: Number(tableId) || undefined }}
                        >
                            <Row gutter={24}>
                                <Col xs={24} sm={12}>
                                    <Form.Item
                                        name="tableId"
                                        label="选择餐桌"
                                        rules={[{ required: true, message: '请选择餐桌' }]}
                                    >
                                        <Select placeholder="请选择餐桌" disabled={!!tableId}>
                                            {tableList.map((table) => (
                                                <Option key={table.id} value={table.id}>
                                                    {table.name}
                                                </Option>
                                            ))}
                                        </Select>
                                    </Form.Item>
                                </Col>
                                <Col xs={24} sm={12}>
                                    <Form.Item name="seat" label="就餐人数">
                                        <InputNumber min={1} style={{ width: '100%' }} placeholder="请输入就餐人数" />
                                    </Form.Item>
                                </Col>
                            </Row>

                            <Form.Item name="remark" label="备注">
                                <Input.TextArea rows={4} placeholder="请输入备注信息" />
                            </Form.Item>
                        </Form>
                    </Card>

                    {/* 订单预览和操作区域 */}
                    <Card title="订单预览" style={{ marginTop: 24 }} bordered={false}>
                        <Row gutter={24}>
                            <Col xs={24} md={16}>
                                {orderParams.tradeOrderList && orderParams.tradeOrderList?.length > 0 ? (
                                    <div>
                                        <Text>已选商品: {orderParams.tradeOrderList.length}件</Text>
                                        <div style={{ marginTop: 16, marginBottom: 16 }}>
                                            {orderParams.tradeOrderList?.map((item: any, index: number) => (
                                                <div key={index} style={{ marginBottom: 8 }}>
                                                    <Space>
                                                        <Text>{item.productName}</Text>
                                                        {item.variantName && <Text type="secondary">({item.variantName})</Text>}
                                                        <Text type="secondary">x{item.quantity}</Text>
                                                    </Space>
                                                </div>
                                            ))}
                                        </div>

                                        {orderPreview && (
                                            <div style={{ marginTop: 16 }}>
                                                <Divider />
                                                {/* <Row justify="space-between" style={{ marginBottom: 8 }}>
                                                    <Col>原价总额:</Col>
                                                    <Col>¥{orderPreview.originAmount}</Col>
                                                </Row> */}
                                                {orderPreview.discountAmount > 0 && (
                                                    <Row justify="space-between" style={{ marginBottom: 8 }}>
                                                        <Col>折扣金额:</Col>
                                                        <Col>-¥{orderPreview.discountAmount}</Col>
                                                    </Row>
                                                )}
                                                <Row justify="space-between" style={{ marginBottom: 8 }}>
                                                    <Col><Text strong>应付金额:</Text></Col>
                                                    <Col><Text strong style={{ color: '#ff4d4f', fontSize: 16 }}>¥{orderPreview.totalAmount}</Text></Col>
                                                </Row>
                                            </div>
                                        )}
                                    </div>
                                ) : (
                                    <Empty description="请选择商品" />
                                )}
                            </Col>
                            <Col xs={24} md={8}>
                                <div style={{ textAlign: 'right' }}>
                                    <Space direction="vertical" style={{ width: '100%' }}>
                                        <Button
                                            type="primary"
                                            size="large"
                                            icon={<ShoppingCartOutlined />}
                                            onClick={handleSubmit}
                                            loading={submitting}
                                            disabled={!orderParams.tradeOrderList || orderParams.tradeOrderList?.length === 0}
                                            style={{ width: '100%' }}
                                        >
                                            提交订单
                                        </Button>
                                        {/* <Button 
                                            style={{ width: '100%' }} 
                                            onClick={handleReset}
                                        >
                                            重置表单
                                        </Button> */}
                                    </Space>
                                </div>
                            </Col>
                        </Row>
                    </Card>
                </Col>
            </Row>
        </Spin>
    );

    return (
        <PageContainer
            title="创建订单"
            onBack={handleBack}
        >
            {orderSuccess ? renderSuccess() : renderOrderForm()}
        </PageContainer>
    );
};

export default OrderFormPage;